package com.kczd.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.kczd.client.R;
import com.kczd.fragment.OrderNotFragment;
import com.kczd.util.ClientIp;
import com.kczd.util.Common;
import com.kczd.util.SysApplication;
import com.swwx.paymax.PayResult;
import com.swwx.paymax.PaymaxCallback;
import com.swwx.paymax.PaymaxSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//未支付订单
public class OrderNotDetailActivity extends AppCompatActivity implements PaymaxCallback,View.OnClickListener{

    private static final String TAG = "OrderNotDetailActivity";

    private TextView mPrice;
    private TextView tv_datetime;
    private TextView tv_oriposition;
    private TextView tv_terposition;

    private int channel = PaymaxSDK.CHANNEL_ALIPAY;
    private String id="";
    private String okey="";
    private String mDriverNum="";
    String callurl = Common.net_addr +"itf/tx_retrieve.php";
    String url = Common.net_addr +"itf/tx_pay.php";

    private String startPos,endPos,amount,startlat,startlgt,endlat,endlgt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_not_detail);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        int position = bundle.getInt("position");

        initView();
        initViewData(position);

        // 多activity管理
        SysApplication.getInstance().addActivity(this);
    }

    private void initView() {
        mPrice= (TextView) findViewById(R.id.d_amount);//车费合计
        tv_datetime = (TextView) findViewById(R.id.tv_datetime);
        tv_oriposition = (TextView) findViewById(R.id.tv_oriposition);
        tv_terposition = (TextView) findViewById(R.id.tv_terposition);
    }

    private void initViewData(int position) {

        mPrice.setText(OrderNotFragment.orderNotlsit.get(position).getTol_price());
        tv_datetime.setText(OrderNotFragment.orderNotlsit.get(position).getDatetime());
        tv_oriposition.setText(OrderNotFragment.orderNotlsit.get(position).getOrigin());
        tv_terposition.setText(OrderNotFragment.orderNotlsit.get(position).getTerminal());

        startPos=OrderNotFragment.orderNotlsit.get(position).getOrigin();
        endPos=OrderNotFragment.orderNotlsit.get(position).getTerminal();
        startlat=OrderNotFragment.orderNotlsit.get(position).getOrigin_lat();
        startlgt=OrderNotFragment.orderNotlsit.get(position).getOrigin_lng();
        endlat=OrderNotFragment.orderNotlsit.get(position).getTerminal_lat();
        endlgt=OrderNotFragment.orderNotlsit.get(position).getTerminal_lng();
        okey=OrderNotFragment.orderNotlsit.get(position).getOkey();

    }
    public void onCharge(View view) {
         amount = mPrice.getText().toString();
        if (checkInputValid(amount)) {
            switch (channel) {
                case PaymaxSDK.CHANNEL_ALIPAY:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            loginHandle();
                        }
                    }).start();
                    break;
            }
        }
    }
    private boolean checkInputValid(String amountText) {
        return !(null == amountText || amountText.length() == 0);
    }

    public void loginHandle() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("ukey", Common.user.getUkey())
                .add("startPos",startPos)
                .add("start_lat", startlat)
                .add("start_lgt", startlgt)
                .add("endPos", endPos)
                .add("end_lat", endlat)
                .add("end_lgt", endlgt)
                .add("amount", amount)
                .add("subject", "打车")
                .add("body", startPos+"--"+endPos)
                .add("channel","alipay_app")
                .add("client_ip", ClientIp.getIPAddress(this))
                .build();

        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();

            if(response.code() == 200) {
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("ret_json", strResult);
                msg.setData(data);
                handle.sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e("val",val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonObject=null;
            try {
                jsonObject=new JSONObject(val);
                id=jsonObject.getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("zhangy",val);
            PaymaxSDK.pay(OrderNotDetailActivity.this,val,OrderNotDetailActivity.this);
            finish();
        }
    };

    @Override
    public void onPayFinished(PayResult result) {
        String msg = "Unknow";
        switch (result.getCode()) {
            case PaymaxSDK.CODE_SUCCESS:
                msg = "Complete, Success!.";
                Log.e("id",id);
                if(id!=null){
                    OkHttpClient okHttpClient=new OkHttpClient();
                    RequestBody requestBody=new FormBody.Builder()
                            .add("id",id)
                            .build();
                    Request request=new Request.Builder()
                            .url(callurl)
                            .post(requestBody)
                            .build();
                    try {
                        Response response=okHttpClient.newCall(request).execute();
                        if(response.code() == 200) {
                            Log.e("zhangyss","pay sucess!");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PaymaxSDK.CODE_ERROR_CHARGE_JSON:
                msg = "Json error.";
                break;

            case PaymaxSDK.CODE_FAIL_CANCEL:
                msg = "cancel pay.";
                break;

            case PaymaxSDK.CODE_ERROR_CHARGE_PARAMETER:
                msg = "appid error.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_NOT_INSTALL:
                msg = "wx not install.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_NOT_SUPPORT_PAY:
                msg = "ex not support pay.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_UNKNOW:
                msg = "wechat failed.";
                break;

            case PaymaxSDK.CODE_ERROR_ALI_DEAL:
                msg = "alipay dealing.";
                break;

            case PaymaxSDK.CODE_ERROR_ALI_CONNECT:
                msg = "alipay network connection failed.";
                break;

            case PaymaxSDK.CODE_ERROR_CHANNEL:
                msg = "channel error.";
                break;
        }
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_back:
                this.finish();
                break;

            default:
                break;
        }
    }
}

